import React from 'react'

// connect方法的作用：将额外的props传递给组件，并返回新的组件，组件在该过程中不会受到影响
import { connect } from 'react-redux'
// 引入action
import { login } from '../../store/common/action.js'
// 引入antd
import { Form, Icon, Input, Button } from 'antd'
import './index.css'

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }
  componentDidMount() {
    document.addEventListener("keydown", this.handleEnterKey);
  }
  componentWillUmount() {
    document.removeEventListener("keydown", this.handleEenterKey);
  }
  // 登录按钮
  handleSubmit = (e) => {
    e.preventDefault();
    let { login } = this.props; // action中的登录方法
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // console.log(values.userName)
        // console.log(values.password)
        // console.log(values.remember)
        // 调用props中的登录方法
        login(values.userName, values.password);
      }
    });
  }
  // 回车登录
  handleEnterKey = (e) => {
    if (e.keyCode === 13) {
      e.preventDefault();
      let { login } = this.props; // action中的登录方法
      this.props.form.validateFields((err, values) => {
        if (!err) {
          // 调用props中的登录方法
          login(values.userName, values.password);
        }
      });
    }
  }
  componentWillReceiveProps(nextProps) {

  }
  componentDidUpdate() {

  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <Form.Item>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: '用户名不能为空' }],
          })(
            <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '密码不能为空' }],
          })(
            <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登录
          </Button>
        </Form.Item>
      </Form>
    );
  }
}
// 将state映射到组件的props中
const mapStateToProps = (state, ownProps) => {
  return {

  }
}
// 将dispatch映射到组件props中
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    login(name, password) {
      dispatch(login(name, password))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(Login));
// export default Form.create()(Login);